package org.itcast.travel.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.itcast.travel.exception.LoginErrException;
import org.itcast.travel.exception.UpdPwdExcepton;
import org.itcast.travel.mapper.UserInfoMapper;
import org.itcast.travel.mapper.UserMapper;
import org.itcast.travel.pojo.LoginInfo;
import org.itcast.travel.pojo.User;
import org.itcast.travel.pojo.UserInfo;
import org.itcast.travel.pojo.UserInfoS;
import org.itcast.travel.service.UserService;
import org.itcast.travel.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    //登录
    @Override
    public LoginInfo login(User user) throws LoginErrException {
        LoginInfo userLogin=userMapper.login(user);
        if (userLogin != null){
            if (userLogin.getState() == 0){
                throw new LoginErrException("账号不存在");
            }
            //生成一个令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", userLogin.getId());
            claims.put("username", userLogin.getUsername());
            String s = JwtUtils.generateJwt(claims);
            return new LoginInfo(userLogin.getId(),userLogin.getUsername(),userLogin.getName(),s,1);
        }else{
            throw new LoginErrException("用户名或密码错误");
        }


    }
    //注册
    @Transactional
    @Override
    public void register(UserInfoS userInfoS) {

        userInfoS.setCreateTime(LocalDateTime.now());
        userInfoS.setUpdateTime(LocalDateTime.now());
        //添加密码用户名
        userMapper.register(userInfoS);
        //用户信息添加
        userInfoMapper.register(userInfoS);
    }
//    获取用户信息
    @Override
    public UserInfo getById(Integer id) {
         UserInfo userInfo=userInfoMapper.getById(id);
         return userInfo;
    }
//    修改用户信息
    @Override
    public void updateUser(UserInfo userInfo) {
        userInfoMapper.updateUser(userInfo);
    }
//逻辑注销用户
    @Override
    public void delUser(Integer id) {
        userMapper.delUser(id);
    }
//修改密码
    @Override
    public void updateUserPasswrod(User user) throws UpdPwdExcepton {
        String newPwd = user.getPassword();
        User userPwd=userMapper.selectByUsername(user.getUsername());
        log.info("new{},old{}",newPwd,userPwd.getPassword());
       if (newPwd.equals(userPwd.getPassword())){
           throw new UpdPwdExcepton("新密码不能与旧密码相同");
       }
        userMapper.updateUserPasswrod(user);
    }
}
